package com.minio.project.Utils;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.MinioException;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @PACKAGE_NAME: com.minio.project.Utils
 * @NAME: MinioUtil
 * @USER: ASUS
 * @DATE: 18/4/2025
 * @TIME: 下午2:48
 **/
@Component
@Data
public class MinioUtil {

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKeyId;
    @Value("${minio.secret}")
    private String secret;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.url}")
    private String url;

    /**
     * 初始化 minio
     * @return
     */
    private MinioClient getMinioClient() {
        MinioClient client = new MinioClient.Builder().credentials(accessKeyId, secret).endpoint(endpoint).build();
        return client;
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @SneakyThrows
    public Map<String, Object> upload(MultipartFile file) {
        if (file == null || file.getSize() == 0)
            throw new RuntimeException("文件大小不能为空");
        String filename = file.getOriginalFilename();
        String fileType = file.getContentType();
        InputStream inputStream = file.getInputStream();
        MinioClient client = getMinioClient();

        client.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(filename)
                        .stream(inputStream, file.getSize(), -1)
                        .contentType(fileType)
                        .build());
        HashMap<String, Object> map = new HashMap<>();
        String fileUrl = this.url + "/" + filename;
        map.put("url", fileUrl);
        map.put("key", filename);
        inputStream.close();
        return map;
    }

    /**
     * 删除文件
     *
     * @param objectName
     * @return
     */
    @SneakyThrows
    public boolean deleteFile(String objectName) {
        MinioClient client = getMinioClient();
        client.removeObject(RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build());
        return true;
    }

}
